/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import Conexion.Conexion;
import RRHH_MODELO.CON_DATOS_EMPRESA;
import RRHH_MODELO.RHH_CATEGORIA_DATO;
import RRHH_MODELO.RHH_DATOS;
import RRHH_MODELO.RHH_PERSONA;
import RRHH_MODELO.RHH_PERSONA_DATOS;
import RRHH_MODELO.RHH_PERSONA_PROFESION;
import RRHH_MODELO.RHH_POSTULADO;
import RRHH_MODELO.mail;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


/**
 *
 * @author equipo_4
 */
@MultipartConfig
@WebServlet(name = "loguin", urlPatterns = {"/loguin"})
public class loguin extends HttpServlet {      

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet loguin</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet loguin at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String evento = request.getParameter("evento");
            String html="";
            
            switch(evento)
            {
                case "logueo":
                html=logueo(request);
                break;
                case "registro":
                html=registro(request);
                break;
                case "reenviarPass":
                html=reenviarPass(request);
                break;
            }
            
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            response.getWriter().write(html);
        } catch (SQLException ex) {
            Logger.getLogger(loguin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

   
    private String logueo(HttpServletRequest request) throws SQLException {
        Conexion con = new Conexion();
        String usuario = request.getParameter("usr");
        String pass = request.getParameter("pass");
        
        RHH_PERSONA pers = new RHH_PERSONA(con).Buscar(usuario);
        if(pers!=null)
        {
            RHH_POSTULADO post = new RHH_POSTULADO(con).BuscarXPersona(pers.getID());
            con.Close();
            if(post!=null)
            {
                if(post.verificarPass(pass))
                {
                    request.getSession().setAttribute("postulado", post);
                    return "true";
                }
                else 
                    return "2";
            }
            else
                return "false";
        }
        else
        {
            return "false";
        }
    }

    private String registro(HttpServletRequest request) {
        Conexion con = new Conexion();
        String ci = request.getParameter("ci");
        String depto = request.getParameter("depto");
        String nom1  = request.getParameter("nombre1");
        String nom2  = request.getParameter("nombre2");
        String apepat = request.getParameter("apepat");
        String apemat  = request.getParameter("apemat");
        String email  = request.getParameter("email");
        String telf  = request.getParameter("telf");
        int prof  = Integer.parseInt(request.getParameter("prof"));
        int anos = Integer.parseInt(request.getParameter("anos"));
        
        
       try
        {         
            
            Part part = request.getPart("curr");                                              
            InputStream in = part.getInputStream();                
            String nombre = "curriculum_"+part.getSubmittedFileName(); 
            long size = part.getSize();
            subirftp(in, ci+"", nombre, size,"");
            in.close();       
            
            con.Transacction();
            RHH_PERSONA per = new RHH_PERSONA(0, Integer.parseInt(ci), depto, nom1, nom2, apepat, apemat,nombre, email, telf, null);
            per.setCon(con);
            int idper = per.Insertar();
            
            RHH_PERSONA_PROFESION pp = new RHH_PERSONA_PROFESION(idper, prof, anos);
            pp.setCon(con);
            pp.Insertar();
            
            String[] letras = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                              "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
            String pass="";
            int letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
             RHH_POSTULADO postu = new RHH_POSTULADO(0, idper, pass);
            postu.setCon(con);
            postu.Insertar();
            CON_DATOS_EMPRESA emp = new CON_DATOS_EMPRESA();
            emp.setCon(con);
            emp.Buscar();
            mail me = new mail(email, "CONVOCATORIA ", ci+"", pass, apepat,emp.getRAZON_SOCIAL());
            con.commit();
            con.Close();
            return true+"";
        }
        catch(Exception e)
        {
            e.printStackTrace();
            con.rollback();
            con.Close();
            return "false";
        }
    }

     private void subirftp(InputStream in, String ci, String nombre, long size,String old) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException
    {
        FTPClient client = new FTPClient();          
        client.connect("192.168.0.101");
        client.login("postulado","oracle123");
        
        try{
            client.createDirectory(ci);
            client.changeDirectory(ci);
        }
        catch(Exception e)
        {
            client.changeDirectory(ci);
        }
        try{
            client.deleteFile(old);
        }catch(Exception e){}                
        client.upload(nombre, in, size, 0, null);
        
        client.disconnect(false);
    }
    
    private String reenviarPass(HttpServletRequest request) {
        String ci = request.getParameter("usr");
        Conexion con = new Conexion();
        try {            
            con.Transacction();
            RHH_PERSONA per = new RHH_PERSONA(con).Buscar(ci);
            RHH_POSTULADO post = new RHH_POSTULADO(con).BuscarXPersona(per.getID());
            
            String[] letras = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                              "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
            String pass="";
            int letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            letra = (int)(Math.random()*52);
            pass+=letras[letra];
            
            post.cambiarPass(pass);
            CON_DATOS_EMPRESA emp = new CON_DATOS_EMPRESA();
            emp.setCon(con);
            emp=emp.Buscar();
            mail me = new mail(per.getEMAIL(), "CONVOCATORIA ", per.getCI()+"", pass, per.getPRIMER_APELLIDO(),emp.getRAZON_SOCIAL());
            con.commit();
            con.Close();
            return "Su contraceña a sido reenviada a "+per.getEMAIL();
            
        } 
        catch (SQLException ex) 
        {
            con.rollback();
            con.Close();
            return "ERROR EN LA TRANSACCION";
        }
        
    }        
}
